home *** CD-ROM | disk | FTP | other *** search
/ Hardcore Visual Basic 5.0 (2nd Edition) / Hardcore Visual Basic 5.0 - Second Edition (1997)(Microsoft Press).iso / Code / Sieve.bas < prev    next >
BASIC Source File  |  1997-06-14  |  1KB  |  31 lines

  1. Attribute VB_Name = "MSieve"
  2. Option Explicit
  3.  
  4. ' Eratosthenes Sieve Prime Number function based on C version Byte magazine, 1/83
  5.  
  6. Function Sieve(ai() As Integer) As Integer
  7.     Dim iLast As Integer, cPrime As Integer, iCur As Integer, i As Integer
  8.     Dim af() As Boolean
  9.     ' Parameter should have dynamic array for maximum number of primes
  10.     If LBound(ai) <> 0 Then Exit Function
  11.     iLast = UBound(ai)
  12.     ' Create array large enough for maximum prime (initializing to zero)
  13.     ReDim af(0 To iLast + 1) As Boolean
  14.     For iCur = 2 To iLast
  15.         ' Anything still zero is a prime
  16.         If Not af(iCur) Then
  17.             ' Cancel its multiples because they can't be prime
  18.             For i = iCur + iCur To iLast Step iCur
  19.                 af(i) = True
  20.             Next
  21.             ' Count this prime
  22.             ai(cPrime) = iCur
  23.             cPrime = cPrime + 1
  24.         End If
  25.     Next
  26.     ' Resize array to the number of primes found
  27.     ReDim Preserve ai(0 To cPrime) As Integer
  28.     Sieve = cPrime
  29. End Function
  30.  
  31.